﻿using System;
using System.ComponentModel;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace QA.TFS.Conditions
{
    [DisplayName("ContextParameter Is Null or Empty")]
    [Description("Condition if the ContextParameter is Null or Empty.")]
    public class ContextParameterIsNullOrEmpty : ConditionalRule
    {

        private string _ContextParameterName = string.Empty;

        [DisplayName("ContextParameter Name")]
        [Description("ContextParameter Name.")]
        public string ContextParameterName
        {
            get { return _ContextParameterName; }
            set { _ContextParameterName = value; }
        }


        private bool _passIfFound = true;

        [DisplayName("Pass If Text Found")]
        [Description("Condition passes if the text is found when this property is set true, or when the text is not found and this property is set false.")]
        [DefaultValue(true)]
        public bool PassIfFound { get { return _passIfFound; } set { _passIfFound = value; } }

        /// <summary>
        /// Determines whether the condition was met or not.
        /// </summary>
        /// <param name="sender">The sender of the event.</param>
        /// <param name="e">The Microsoft.VisualStudio.TestTools.WebTesting.ConditionalEventArgs that contains the event data.</param>
        public override void CheckCondition(object sender, ConditionalEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(_ContextParameterName.Trim()))
                {
                    e.WebTest.Stop();
                    throw new WebTestException("Parametro obligatorio no puede ser nulo");
                }

                string contextParameterValue = e.WebTest.Context[_ContextParameterName].ToString();

                if (string.IsNullOrEmpty(contextParameterValue.Trim()))
                    e.IsMet = true;
                else if (contextParameterValue.Trim().ToLowerInvariant().Equals((string)"null"))
                    e.IsMet = true;
                else
                    e.IsMet = false;

                if (!_passIfFound)
                    e.IsMet = !e.IsMet;
            }
            catch (Exception ex)
            {
                e.Message = ex.Message;
                e.IsMet = false;
            }
        }
    }

}
